package com.dgj.utils.baidu.location;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.nutz.json.Json;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Logs;

import com.dgj.utils.baidu.common.BaiduApiInvoker;
import com.dgj.utils.baidu.common.JsonBean;
import com.dgj.utils.baidu.location.BaiduNuomi.City.District;
import com.dgj.utils.baidu.location.BaiduNuomi.City.District.BizArea;
import com.dgj.utils.collection.Lists;

/**
 * 百度糯米接口
 * 
 * @author 王贵源
 * @email kerbores@dgj.com
 *
 *        create at 2015年10月16日 下午1:00:27
 */
public class BaiduNuomi extends BaiduApiInvoker {
	protected static String ERROR_CODE_KEY = "errno";
	protected static String DATA_KEY = "cities";
	protected static String ERROR_MSG_KEY = "msg";

	public static class City extends JsonBean {
		private String id;
		private String name;
		private String shortName;
		private String pinyin;
		private String shortPinyin;

		/**
		 * @return the id
		 */
		public String getId() {
			return id;
		}

		/**
		 * @param id
		 *            the id to set
		 */
		public void setId(String id) {
			this.id = id;
		}

		/**
		 * @return the name
		 */
		public String getName() {
			return name;
		}

		/**
		 * @param name
		 *            the name to set
		 */
		public void setName(String name) {
			this.name = name;
		}

		/**
		 * @return the shortName
		 */
		public String getShortName() {
			return shortName;
		}

		/**
		 * @param shortName
		 *            the shortName to set
		 */
		public void setShortName(String shortName) {
			this.shortName = shortName;
		}

		/**
		 * @return the pinyin
		 */
		public String getPinyin() {
			return pinyin;
		}

		/**
		 * @param pinyin
		 *            the pinyin to set
		 */
		public void setPinyin(String pinyin) {
			this.pinyin = pinyin;
		}

		/**
		 * @return the shortPinyin
		 */
		public String getShortPinyin() {
			return shortPinyin;
		}

		/**
		 * @param shortPinyin
		 *            the shortPinyin to set
		 */
		public void setShortPinyin(String shortPinyin) {
			this.shortPinyin = shortPinyin;
		}

		public static class District extends JsonBean {
			/**
			 * 编号
			 */
			private String id;
			/**
			 * 名称
			 */
			private String name;
			/**
			 * 商圈列表
			 */
			List<BizArea> bizAreas;

			/**
			 * @return the id
			 */
			public String getId() {
				return id;
			}

			/**
			 * @param id
			 *            the id to set
			 */
			public void setId(String id) {
				this.id = id;
			}

			/**
			 * @return the name
			 */
			public String getName() {
				return name;
			}

			/**
			 * @param name
			 *            the name to set
			 */
			public void setName(String name) {
				this.name = name;
			}

			/**
			 * @return the bizAreas
			 */
			public List<BizArea> getBizAreas() {
				return bizAreas;
			}

			/**
			 * @param bizAreas
			 *            the bizAreas to set
			 */
			public void setBizAreas(List<BizArea> bizAreas) {
				this.bizAreas = bizAreas;
			}

			public static class BizArea extends JsonBean {
				/**
				 * 编号
				 */
				private String id;
				/**
				 * 名称
				 */
				private String name;

				/**
				 * @return the id
				 */
				public String getId() {
					return id;
				}

				/**
				 * @param id
				 *            the id to set
				 */
				public void setId(String id) {
					this.id = id;
				}

				/**
				 * @return the name
				 */
				public String getName() {
					return name;
				}

				/**
				 * @param name
				 *            the name to set
				 */
				public void setName(String name) {
					this.name = name;
				}

			}
		}
	}

	public static void main(String[] args) {
		System.err.println(listCitys());
		System.err.println(listDistrictsByCityId("900010000"));// 重庆商圈
	}

	/**
	 * @param urlAll
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;

		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("apikey", "4a6cfff3a7840913094a7cbb67d79537");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 行政区划
	 * 
	 * @param cityId
	 * @return
	 */
	public static List<District> listDistrictsByCityId(String cityId) {
		String httpUrl = "http://apis.baidu.com/baidunuomi/openapi/districts";
		String httpArg = "city_id=" + cityId;
		String jsonResult = request(httpUrl, httpArg);
		NutMap map = NutMap.WRAP((Map<String, Object>) Json.fromJson(jsonResult));
		final List<District> districts = Lists.newArrayList();
		if (map.getInt("errno") == 0) {
			Lang.each(map.getList("districts", NutMap.class), new Each<NutMap>() {

				@Override
				public void invoke(int paramInt1, NutMap map, int paramInt2) throws ExitLoop, ContinueLoop, LoopException {
					District district = new District();
					district.setId(map.getString("district_id"));
					district.setName(map.getString("district_name"));
					final List<BizArea> areas = Lists.newArrayList();
					Lang.each(map.getList("biz_areas", NutMap.class), new Each<NutMap>() {

						@Override
						public void invoke(int paramInt1, NutMap map, int paramInt2) throws ExitLoop, ContinueLoop, LoopException {
							BizArea area = new BizArea();
							area.setId(map.getString("biz_area_id"));
							area.setName(map.getString("biz_area_name"));
							areas.add(area);
						}
					});
					district.setBizAreas(areas);
					districts.add(district);
				}
			});
		} else {
			Logs.get().debug("调用错误, code: " + map.getInt("errno") + " msg: " + map.getString("msg"));
		}
		return districts;
	}

	public static List<City> listCitys() {
		String httpUrl = "http://apis.baidu.com/baidunuomi/openapi/cities";
		String httpArg = "";
		String jsonResult = request(httpUrl, httpArg);
		NutMap map = NutMap.WRAP((Map<String, Object>) Json.fromJson(jsonResult));
		final List<City> citys = Lists.newArrayList();
		if (map.getInt("errno") == 0) {
			Lang.each(map.getList("cities", NutMap.class), new Each<NutMap>() {

				@Override
				public void invoke(int paramInt1, NutMap map, int paramInt2) throws ExitLoop, ContinueLoop, LoopException {
					City temp = new City();
					temp.setId(map.getString("city_id"));
					temp.setName(map.getString("city_name"));
					temp.setShortName(map.getString("short_name"));
					temp.setPinyin(map.getString("city_pinyin"));
					temp.setShortPinyin(map.getString("short_pinyin"));
					citys.add(temp);
				}
			});
		} else {
			Logs.get().debug("调用错误, code: " + map.getInt("errno") + " msg: " + map.getString("msg"));
		}
		return citys;
	}
}
